package site.zhangzhuo.learn_springboot.postprocessor;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.stereotype.Component;

/**
 * OrangeRegisterPostProcessor是一个BeanDefinitionRegistryPostProcessor。
 * 它的主要作用是检查IOC容器中是否已经包含了名为"orange"的bean定义。
 * 如果没有，它会动态创建一个Orange类的bean定义并注册到容器中。
 */
@Component
public class OrangeRegisterPostProcessor implements BeanDefinitionRegistryPostProcessor {
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        //System.out.println("postProcessBeanDefinitionRegistry in OrangeRegisterPostProcessor started.");
        if (!registry.containsBeanDefinition("orange")) {
            BeanDefinition orangeDefinition = BeanDefinitionBuilder.genericBeanDefinition(Orange.class).getBeanDefinition();
            registry.registerBeanDefinition("orange", orangeDefinition);
        }
        //--------------------------------------------------------------------
        // 创建一个 BeanDefinition
        BeanDefinition beanDefinition = new RootBeanDefinition(MyBean.class);
        // 注册 BeanDefinition
        registry.registerBeanDefinition("myBean", beanDefinition);
        //--------------------------------------------------------------------
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        //System.out.println("postProcessBeanFactory in OrangeRegisterPostProcessor started.");

        //--------------------------------------------------------------------
        // 从 BeanFactory 中获取 Bean
        MyBean myBean = beanFactory.getBean("myBean", MyBean.class);
        // 使用 Bean
        myBean.doSomething();  // 输出：Hello, world!
        //--------------------------------------------------------------------
    }
}
